# x86_64 via qemu + u-boot firmware, for q35 machine type
declare -g UEFI_GRUB="skip" # Skip GRUB for this board
declare -g BOARD_NAME="uefi-x86"
declare -g BOARDFAMILY="uefi-x86"
declare -g BOARD_MAINTAINER="rpardini"
declare -g KERNEL_TARGET="current,edge"

declare -g SERIALCON="ttyS0"

# u-boot's "x86_64" is incomplete; use the 32-bit version.
declare -g QEMU_UBOOT_BOOTCONFIG="qemu-x86_defconfig"
declare -g INITRD_ARCH='x86' # input for mkimage, needed for extlinux

## qemu'ed uboot on x86 can do extlinux?
#declare -g SRC_EXTLINUX="yes"
#declare -g SRC_CMDLINE="loglevel=7 console=ttyS0" # Those boards are serial-debug only; 'root=LABEL=armbi_root' ?
#enable_extension "u-boot-menu"                    # this generates the extlinux.conf

function post_family_config__force_uboot_rom_build_x86() {
	declare -g UBOOT_TARGET_MAP="all;;u-boot.rom" # Can't find the target that produces 'u-boot.rom', so for now 'make all'

	# x86 requires a bootscript, since it's a bzImage and non-mkimage'd initrd; extlinux chokes.
	declare -g BOOTSCRIPT="boot-qemu-x86.cmd:boot.cmd"
}

# Export the u-boot.rom file next to the disk image, so it can be used as qemu's firmware via the -bios option.
function pre_umount_final_image__export_uboot_rom() {
	: "${version:?version is not set}"
	local uboot_name="linux-u-boot-${BRANCH}-${BOARD}"
	display_alert "Exporting u-boot.rom" "${uboot_name} - ${version}.u-boot.rom" "debug"
	run_host_command_logged cp -pv "${MOUNT}/usr/lib/${uboot_name}/u-boot.rom" "${DESTIMG}/${version}.u-boot.rom"
}

function board_docs__qemu-uboot-x86() {
	: "${version:?version is not set}"
	cat <<- DOCS
		## Upstream docs

		- https://u-boot.readthedocs.io/en/latest/arch/x86.html
		- https://u-boot.readthedocs.io/en/latest/board/emulation/qemu-x86.html

		## Running on qemu, via command line

		### On Linux (x86), with KVM acceleration

		\`\`\`bash
		qemu-system-x86_64 -accel kvm -machine q35,vmport=off -smp 8 -nographic -bios ${version}.u-boot.rom -m 2048 -nic user,model=virtio-net-pci -device virtio-blk-pci,drive=drive0,bootindex=0 -drive if=none,media=disk,id=drive0,file=${version}.img.qcow2,discard=unmap,detect-zeroes=unmap
		\`\`\`

		### On Mac (x86)

		\`\`\`bash
		# -accel hvf does not work for me, u-boot hangs. this makes it unpractical on macos (monterey). probably also works under darwin/arm64, it's emulated anyway.
		qemu-system-x86_64 -machine q35,vmport=off -smp 8 -nographic -bios ${version}.u-boot.rom -m 2048 -nic user,model=virtio-net-pci -device virtio-blk-pci,drive=drive0,bootindex=0 -drive if=none,media=disk,id=drive0,file=${version}.img.qcow2,discard=unmap,detect-zeroes=unmap
		\`\`\`
	DOCS
}
